package com.diankangwo.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 订单工具类，用来生成订单号
 *
 * @author xiaoyu
 */
public class OrderUtil {

    private static long orderNum = 0l;
    private static String date;

    //声明重入锁
    static ReentrantLock lock = new ReentrantLock();

    /**
     * 生成订单号
     *
     * @return
     */
    public static String getOrderNo() {
        try {
            lock.lock();
            String str = new SimpleDateFormat("yyMMddHHmm").format(new Date());
            if (date == null || !date.equals(str)) {
                date = str;
                orderNum = 0l;
            }
            orderNum++;
            long orderNo = Long.parseLong((date)) * 10000;
            orderNo += orderNum;
            return orderNo + "";
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            lock.unlock();
        }

    }

    /**
     * @描述 java生成流水号
     * 14位时间戳 + 6位随机数
     * @参数:@return
     * @返回值：String
     */
    public static String getNumberForPK() {
        try {
            lock.lock();
            String str = new SimpleDateFormat("yyyyMMdd").format(new Date());
            int random = (int) (Math.random() * 10000);
            return str + random;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            lock.unlock();
        }

    }

}
